# -*- coding: utf-8 -*-
#Menu shit

import pygame
from pygame.constants import *
import sys, os

import game
import data
import credits
import popup
import default
import sound

class Menuentry(pygame.sprite.Sprite):
    def __init__(self, text, action, pos, args):
        pygame.sprite.Sprite.__init__(self)
        
        self.font = pygame.font.Font(default.font, 45)
        
        self.text = text
        
        self.unselect()
        
        self.rect = self.image.get_rect()
        self.rect.topleft = pos
                
        self.action = action

        self.args = args

    def select(self):
        #Greyish looks transparent. Red is better
        self.color = (215, 13, 32)#200,20,24)
        self.render()
        return self

    def unselect(self):
        self.color = (50,50,50)
        self.render()
        
    def render(self):
        #ANTIALIASED FUCKING FONTS CAN'T BE FUCKING ALPHA'D FUCKING FUCK!
        self.image = self.font.render(self.text, False, self.color)
        
    def pressed(self):
        self.action(*self.args)

class Menu:
    def __init__(self, screen, level = 0):
        self.entries = pygame.sprite.Group()
        self.entry = 0
        
        self.level = level
        self.clear()
        
        self.screen = screen
        self.screen_rect = screen.get_rect()
        if self.level == 0:
            self.add_menu_entry("DESTROY-HUMANITY", self.run_game)
            self.add_menu_entry("SELECT-CITY", self.select_level)
            self.add_menu_entry("HOW-DO-I-MAKE-HUMAN-BLEED", self.help)
            self.add_menu_entry("WHO-IS-MY-CREATOR", self.run_credits, None)
            self.add_menu_entry("QUIT-GAME", sys.exit, 0)
            
            #self.selected = self.entry_list[self.entry].select()
        
        self.background, self.bg_rect = data.load_image("menubg.png")#data.load_image("ingame_bg.png")#"menubg.png")
        

    def add_menu_entry(self, text, function, *args):

        pos = ( 20, self.last_entry_bottom + 30)
        entry = Menuentry(text, function, pos, args)
        self.entries.add(entry)
        self.last_entry_bottom = entry.rect.bottom

        #A group has no index, unfortunately
        self.entry_list.append(entry)
        
    def show_entry(self, entry):
        pos = ( 20, self.last_entry_bottom + 30)
        entry.rect.topleft = pos
        self.last_entry_bottom = entry.rect.bottom
        self.entries.add(entry)
        
        
    def run_credits(self, args):
        credits.run(self.screen)
        sound.play_music("robot_title.ogg")

    def help(self):
        for page in default.game_help:
            helptext = popup.popup(page, (255,255,255), (0,0,0))
            helptext.set_alpha(200)
            help_rect = helptext.get_rect()
            next = False
            
            while not next:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        #We don't wanna quit without asking first. That's rude.
                        sys.exit(0)
                    if event.type == KEYDOWN:
                        if event.key == K_RETURN:
                            next = True
                            
                self.screen.blit(self.background, (0,0))
                self.entries.draw(self.screen)
                pos = (self.screen_rect.centerx - help_rect.w/2,
                       self.screen_rect.centery - help_rect.h/2) 
                self.screen.blit( helptext, pos )
                pygame.display.flip()
    
    def run(self):
        sound.play_music("robot_title.ogg")
        self.scroll(0) #required
        while True:
            if self.check():
                return
            self.screen.blit(self.background, (0,0))
            self.entries.draw(self.screen)
            pygame.display.flip()
            
    def clear(self):
        self.entries.empty()
        self.entry_list = []
        self.last_entry_bottom = 0
        #self.entry = 0 #index in list
            
    def check(self):        
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
                
            if event.type == KEYDOWN:
                if event.key == K_UP:
                    self.scroll(-1)
                    
                if event.key == K_DOWN:
                    self.scroll(1)
                    
                if event.key == K_RETURN or event.key == K_SPACE:
                    self.selected.pressed()
                if event.key == K_ESCAPE: #I have missed this..
                    return True
            
            
    def run_game(self, nr = 0): #nödlösning
        le_game = game.Game(self.screen, nr)
        le_game.run()
        sound.play_music("robot_title.ogg")
        if self.level != 0:
            self.clear()
            self.draw_select()
            self.scroll(0) #This should not be needed. Put show_entries somewhere else, for fuck's sake!

    def select_level(self):
        selector = Menu(self.screen, 1)
        selector.draw_select()
        
        selector.run()
    
    def draw_select(self):
        try:
            file = open(os.path.join(data.data_dir, "unlocked"), "r")
        except IOError:
            file = open(os.path.join(data.data_dir, "unlocked"), "w")
            file.write("0\n")
            file.close()
            file = open(os.path.join(data.data_dir, "unlocked"), "r")

            
        for line in file:
            self.add_menu_entry("PLAY-CITY-" + line.strip(), self.run_game, int(line))
        #self.selected = self.entry_list[0].select()
        #self.entry = 0 
    
    def scroll(self, step):
        sound.play_sound("select.wav")
        
        if self.entry < len(self.entry_list):
            self.entry_list[self.entry].unselect()
        
        self.entries.empty()
        self.last_entry_bottom = 0
        
        self.entry += step
        try:
            self.entry %= len(self.entry_list)
        except ZeroDivisionError:
            pass #shit happens
        
        #probably a hack. I pallar not
        if self.entry - 2 < 0:
            tehlist = self.entry_list[self.entry - 2:] + self.entry_list[:self.entry + 3]
        elif self.entry + 3 > len(self.entry_list):
            tehlist = self.entry_list[self.entry - 2:] + self.entry_list[: (self.entry + 3) % len(self.entry_list) ]
        else:
            tehlist = self.entry_list[self.entry - 2:self.entry + 3]

        for i in xrange(len(tehlist)):
            tehlist[i].image.set_alpha(255 - 60*(i - 2)**2 + 50, RLEACCEL)
        for entry in tehlist:
            self.show_entry(entry)
        #nr = len(tehlist)/2

        self.selected = self.entry_list[self.entry].select()



